<template>
  <div class="markdown-editor">
    <!-- 编辑器头部 -->
    <div class="editor-header">
      <div class="editor-tabs">
        <el-radio-group v-model="activeTab" size="small">
          <el-radio-button value="edit">编辑</el-radio-button>
          <el-radio-button value="preview">预览</el-radio-button>
          <el-radio-button value="split">分屏</el-radio-button>
        </el-radio-group>
      </div>
      
      <div class="editor-actions">
        <el-button-group size="small">
          <el-button @click="insertBold">
            <strong>B</strong>
          </el-button>
          <el-button @click="insertItalic">
            <em>I</em>
          </el-button>
          <el-button @click="insertCode">
            <code>{}</code>
          </el-button>
          <el-button @click="insertLink">
            🔗
          </el-button>
          <el-button @click="insertImage">
            🖼️
          </el-button>
        </el-button-group>
        
        <el-button size="small" type="primary" @click="saveContent">
          <el-icon><Document /></el-icon>
          保存
        </el-button>
      </div>
    </div>
    
    <!-- 编辑器主体 -->
    <div class="editor-body">
      <!-- 仅编辑模式 -->
      <div v-if="activeTab === 'edit'" class="editor-only">
        <el-input
          ref="textareaRef"
          v-model="content"
          type="textarea"
          :rows="20"
          placeholder="请输入 Markdown 内容...\n\n💡 提示：可以直接粘贴或拖拽图片到此处，自动上传并插入Markdown语法"
          :class="['markdown-textarea', { 'drag-over': isDragOver }]"
          @input="handleInput"
          @paste="handlePaste"
          @drop="handleDrop"
          @dragover="handleDragOver"
          @dragleave="handleDragLeave"
        />
      </div>
      
      <!-- 仅预览模式 -->
      <div v-else-if="activeTab === 'preview'" class="preview-only">
        <div class="markdown-preview">
          <div v-html="renderedMarkdown" class="markdown-body"></div>
        </div>
      </div>
      
      <!-- 分屏模式 -->
      <div v-else class="split-view">
        <div class="split-editor">
          <div class="split-header">编辑</div>
          <el-input
            v-model="content"
            type="textarea"
            :rows="18"
            placeholder="请输入 Markdown 内容..."
            class="markdown-textarea"
            @input="handleInput"
          />
        </div>
        
        <div class="split-divider"></div>
        
        <div class="split-preview">
          <div class="split-header">预览</div>
          <div class="markdown-preview">
            <div v-html="renderedMarkdown" class="markdown-body"></div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 编辑器底部状态栏 -->
    <div class="editor-footer">
      <div class="editor-stats">
        <el-text size="small" type="info">
          字符数: {{ content.length }} | 
          行数: {{ content.split('\n').length }} | 
          字数: {{ getWordCount() }}
        </el-text>
      </div>
      
      <div class="editor-status">
        <el-text v-if="isModified" size="small" type="warning">
          <el-icon><Warning /></el-icon>
          未保存
        </el-text>
        <el-text v-else size="small" type="success">
          <el-icon><Check /></el-icon>
          已保存
        </el-text>
      </div>
    </div>
    
    <!-- 图片上传对话框 -->
    <el-dialog
      v-model="showImageUploadDialog"
      title="插入图片"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="image-upload-content">
        <el-tabs v-model="imageUploadTab" class="image-upload-tabs">
          <!-- 上传图片 -->
          <el-tab-pane label="上传图片" name="upload">
            <div class="upload-section">
              <el-upload
                ref="imageUploadRef"
                class="image-uploader"
                drag
                :auto-upload="false"
                :show-file-list="false"
                :before-upload="beforeImageUpload"
                :on-change="handleImageChange"
                accept="image/*"
              >
                <div v-if="!imagePreviewUrl" class="upload-area">
                  <el-icon class="upload-icon"><Plus /></el-icon>
                  <div class="upload-text">点击或拖拽图片到此处上传</div>
                  <div class="upload-hint">支持 JPG、PNG、GIF、WebP 格式，大小不超过 5MB</div>
                </div>
                <div v-else class="image-preview">
                  <img :src="imagePreviewUrl" alt="预览图片" />
                  <div class="image-actions">
                    <el-button @click="removeImage" size="small" type="danger">
                      <el-icon><Delete /></el-icon>
                      移除
                    </el-button>
                    <el-button @click="$refs.imageUploadRef.$el.querySelector('input').click()" size="small">
                      <el-icon><Upload /></el-icon>
                      更换
                    </el-button>
                  </div>
                </div>
              </el-upload>
              
              <div class="image-info" v-if="imageFile">
                <el-input
                  v-model="imageAlt"
                  placeholder="请输入图片描述（可选）"
                  class="image-alt-input"
                />
                <el-input
                  v-model="imageCaption"
                  placeholder="请输入图片说明（可选）"
                  class="image-caption-input"
                />
              </div>
            </div>
          </el-tab-pane>
          
          <!-- URL输入 -->
          <el-tab-pane label="图片链接" name="url">
            <div class="url-section">
              <el-input
                v-model="imageUrl"
                placeholder="请输入图片URL"
                class="image-url-input"
              />
              <el-input
                v-model="imageAlt"
                placeholder="请输入图片描述（可选）"
                class="image-alt-input"
              />
              <div v-if="imageUrl" class="url-preview">
                <img :src="imageUrl" alt="预览图片" @error="handleImageError" />
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelImageUpload">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmImageInsert"
            :loading="isUploading"
            :disabled="!canInsertImage"
          >
            {{ isUploading ? '上传中...' : '插入图片' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, defineProps, defineEmits } from 'vue'
import { ElMessage, ElDialog, ElUpload, ElButton } from 'element-plus'
import { 
  Edit, 
  View, 
  Document, 
  Warning, 
  Check,
  Upload,
  Plus,
  Delete
} from '@element-plus/icons-vue'
import apiService from '../services/api.js'

// Props
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请输入 Markdown 内容...'
  },
  height: {
    type: [String, Number],
    default: 500
  }
})

// Events
const emit = defineEmits(['update:modelValue', 'save'])

// 响应式数据
const activeTab = ref('edit')
const content = ref(props.modelValue)
const originalContent = ref(props.modelValue)
const textareaRef = ref()

// 图片上传相关
const showImageUploadDialog = ref(false)
const imageUploadTab = ref('upload')
const imageUploadRef = ref()
const imagePreviewUrl = ref('')
const imageFile = ref(null)
const imageUrl = ref('')
const imageAlt = ref('')
const imageCaption = ref('')
const isUploading = ref(false)
const isDragOver = ref(false)

// 计算属性
const isModified = computed(() => {
  return content.value !== originalContent.value
})

// 是否可以插入图片
const canInsertImage = computed(() => {
  if (imageUploadTab.value === 'upload') {
    return imageFile.value !== null
  } else {
    return imageUrl.value.trim() !== ''
  }
})

// 渲染 Markdown（简单实现，实际项目中建议使用专业的 Markdown 解析库）
const renderedMarkdown = computed(() => {
  if (!content.value) return '<p class="empty-content">暂无内容</p>'
  
  // 简单的 Markdown 转换（实际项目中应使用 marked 或 markdown-it）
  let html = content.value
    // 代码块
    .replace(/```([\s\S]*?)```/gim, '<pre><code>$1</code></pre>')
    // 标题
    .replace(/^### (.*$)/gim, '<h3>$1</h3>')
    .replace(/^## (.*$)/gim, '<h2>$1</h2>')
    .replace(/^# (.*$)/gim, '<h1>$1</h1>')
    // 粗体
    .replace(/\*\*(.*?)\*\*/gim, '<strong>$1</strong>')
    // 斜体
    .replace(/\*(.*?)\*/gim, '<em>$1</em>')
    // 行内代码
    .replace(/`(.*?)`/gim, '<code>$1</code>')
    // 链接
    .replace(/\[([^\]]+)\]\(([^\)]+)\)/gim, '<a href="$2" target="_blank">$1</a>')
    // 图片
    .replace(/!\[([^\]]*)\]\(([^\)]+)\)/gim, '<img src="$2" alt="$1" />')
    // 无序列表
    .replace(/^\* (.*$)/gim, '<li>$1</li>')
    .replace(/(<li>.*<\/li>)/s, '<ul>$1</ul>')
    // 有序列表
    .replace(/^\d+\. (.*$)/gim, '<li>$1</li>')
    // 引用
    .replace(/^> (.*$)/gim, '<blockquote>$1</blockquote>')
    // 分割线
    .replace(/^---$/gim, '<hr>')
    // 换行
    .replace(/\n/gim, '<br>')
  
  return html
})

// 监听 props 变化
watch(() => props.modelValue, (newValue) => {
  content.value = newValue
  originalContent.value = newValue
})

// 监听内容变化
watch(content, (newValue) => {
  emit('update:modelValue', newValue)
})

// 处理输入
const handleInput = () => {
  // 智能检测图片语法
  detectImageSyntax()
  // 可以在这里添加实时保存逻辑
}

// 智能检测图片语法
const detectImageSyntax = () => {
  const textarea = textareaRef.value?.textarea || textareaRef.value
  if (!textarea) return
  
  const cursorPosition = textarea.selectionStart
  const textBeforeCursor = content.value.substring(0, cursorPosition)
  
  // 检测是否刚输入了 ![xxx](img)
  const imagePattern = /!\[([^\]]*)\]\(img\)$/
  const match = textBeforeCursor.match(imagePattern)
  
  if (match) {
    const altText = match[1] || '图片'
    // 移除刚输入的 img 部分
    const beforeMatch = textBeforeCursor.substring(0, match.index)
    const afterCursor = content.value.substring(cursorPosition)
    
    // 创建一个隐藏的文件输入元素
    const fileInput = document.createElement('input')
    fileInput.type = 'file'
    fileInput.accept = 'image/*'
    fileInput.style.display = 'none'
    
    fileInput.onchange = async (event) => {
      const file = event.target.files?.[0]
      if (file && beforeImageUpload(file)) {
        try {
          // 显示上传占位符
          const placeholder = `![${altText}](上传中...)`
          content.value = beforeMatch + placeholder + afterCursor
          
          // 上传图片
          const formData = new FormData()
          formData.append('image', file)
          const response = await apiService.items.uploadImage(formData)
          
          // 替换占位符为实际URL
          const finalMarkdown = `![${altText}](${response.data.url})`
          content.value = content.value.replace(placeholder, finalMarkdown)
          
          ElMessage.success('图片上传成功')
          
          // 设置光标位置
          setTimeout(() => {
            const newPosition = beforeMatch.length + finalMarkdown.length
            textarea.setSelectionRange(newPosition, newPosition)
            textarea.focus()
          }, 0)
        } catch (error) {
          console.error('图片上传失败:', error)
          ElMessage.error('图片上传失败，请重试')
          // 恢复原始文本
          content.value = beforeMatch + `![${altText}](img)` + afterCursor
        }
      }
      // 清理文件输入元素
      document.body.removeChild(fileInput)
    }
    
    // 添加到DOM并触发点击
    document.body.appendChild(fileInput)
    fileInput.click()
  }
}

// 获取字数统计
const getWordCount = () => {
  // 简单的中英文字数统计
  const text = content.value.replace(/[\r\n\s]/g, '')
  const chineseCount = (text.match(/[\u4e00-\u9fa5]/g) || []).length
  const englishCount = (text.match(/[a-zA-Z]+/g) || []).join('').length
  return chineseCount + Math.ceil(englishCount / 4) // 英文按4个字母算一个字
}

// 工具栏操作
const insertBold = () => {
  insertText('**', '**', '粗体文本')
}

const insertItalic = () => {
  insertText('*', '*', '斜体文本')
}

const insertCode = () => {
  insertText('`', '`', '代码')
}

const insertLink = () => {
  insertText('[', '](url)', '链接文本')
}

const insertImage = () => {
  // 重置图片上传状态
  resetImageUploadState()
  showImageUploadDialog.value = true
}

// 插入文本的通用方法
const insertText = (prefix, suffix, placeholder) => {
  const textarea = document.querySelector('.markdown-textarea textarea')
  if (!textarea) return
  
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const selectedText = content.value.substring(start, end)
  const textToInsert = selectedText || placeholder
  
  const newText = content.value.substring(0, start) + 
                  prefix + textToInsert + suffix + 
                  content.value.substring(end)
  
  content.value = newText
  
  // 设置光标位置
  setTimeout(() => {
    const newStart = start + prefix.length
    const newEnd = newStart + textToInsert.length
    textarea.setSelectionRange(newStart, newEnd)
    textarea.focus()
  }, 0)
}

// 保存内容
const saveContent = () => {
  originalContent.value = content.value
  emit('save', content.value)
  ElMessage.success('内容已保存')
}

// 图片上传相关方法
const resetImageUploadState = () => {
  imageUploadTab.value = 'upload'
  imagePreviewUrl.value = ''
  imageFile.value = null
  imageUrl.value = ''
  imageAlt.value = ''
  imageCaption.value = ''
  isUploading.value = false
}

const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB！')
    return false
  }
  return true
}

const handleImageChange = (file) => {
  if (!beforeImageUpload(file.raw)) {
    return
  }
  
  imageFile.value = file.raw
  
  // 创建预览URL
  const reader = new FileReader()
  reader.onload = (e) => {
    imagePreviewUrl.value = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

const removeImage = () => {
  imageFile.value = null
  imagePreviewUrl.value = ''
  if (imageUploadRef.value) {
    imageUploadRef.value.clearFiles()
  }
}

const handleImageError = () => {
  ElMessage.error('图片加载失败，请检查URL是否正确')
}

const uploadImageToServer = async () => {
  if (!imageFile.value) return null
  
  const formData = new FormData()
  formData.append('image', imageFile.value)
  if (imageCaption.value) {
    formData.append('caption', imageCaption.value)
  }
  
  try {
    const response = await apiService.items.uploadImage(formData)
    return response.data.url
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败，请重试')
    throw error
  }
}

const confirmImageInsert = async () => {
  try {
    isUploading.value = true
    let finalImageUrl = ''
    
    if (imageUploadTab.value === 'upload') {
      // 上传图片
      finalImageUrl = await uploadImageToServer()
    } else {
      // 使用URL
      finalImageUrl = imageUrl.value
    }
    
    if (finalImageUrl) {
      // 插入Markdown图片语法
      const altText = imageAlt.value || '图片'
      const markdownImage = `![${altText}](${finalImageUrl})`
      
      // 如果有说明文本，添加到下一行
      const fullMarkdown = imageCaption.value 
        ? `${markdownImage}\n*${imageCaption.value}*`
        : markdownImage
      
      insertTextAtCursor(fullMarkdown)
      
      showImageUploadDialog.value = false
      ElMessage.success('图片插入成功')
    }
  } catch (error) {
    console.error('图片插入失败:', error)
  } finally {
    isUploading.value = false
  }
}

const cancelImageUpload = () => {
  showImageUploadDialog.value = false
  resetImageUploadState()
}

const insertTextAtCursor = (text) => {
  const textarea = document.querySelector('.markdown-textarea textarea')
  if (!textarea) return
  
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  
  const newText = content.value.substring(0, start) + 
                  text + 
                  content.value.substring(end)
  
  content.value = newText
  
  // 设置光标位置到插入文本的末尾
  setTimeout(() => {
    const newPosition = start + text.length
    textarea.setSelectionRange(newPosition, newPosition)
    textarea.focus()
  }, 0)
}

/**
 * 处理图片粘贴事件
 * @param {ClipboardEvent} event - 粘贴事件
 */
const handlePaste = async (event) => {
  const items = event.clipboardData?.items
  if (!items) return

  for (let i = 0; i < items.length; i++) {
    const item = items[i]
    if (item.type.startsWith('image/')) {
      event.preventDefault()
      const file = item.getAsFile()
      if (file) {
        await handleImageFile(file)
      }
      break
    }
  }
}

/**
 * 处理拖拽悬停事件
 * @param {DragEvent} event - 拖拽事件
 */
const handleDragOver = (event) => {
  event.preventDefault()
  event.dataTransfer.dropEffect = 'copy'
  isDragOver.value = true
}

/**
 * 处理拖拽离开事件
 * @param {DragEvent} event - 拖拽事件
 */
const handleDragLeave = (event) => {
  event.preventDefault()
  isDragOver.value = false
}

/**
 * 处理图片拖拽放置事件
 * @param {DragEvent} event - 拖拽事件
 */
const handleDrop = async (event) => {
  event.preventDefault()
  isDragOver.value = false
  
  const files = event.dataTransfer?.files
  if (!files || files.length === 0) return

  for (let i = 0; i < files.length; i++) {
    const file = files[i]
    if (file.type.startsWith('image/')) {
      await handleImageFile(file)
    }
  }
}

/**
 * 处理图片文件上传和插入
 * @param {File} file - 图片文件
 */
const handleImageFile = async (file) => {
  // 验证文件
  if (!beforeImageUpload(file)) {
    return
  }

  try {
    // 获取当前光标位置
    const textarea = textareaRef.value?.$el?.querySelector('textarea')
    const cursorPosition = textarea?.selectionStart || content.value.length

    // 生成唯一标识符
    const uploadId = `uploading-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
    const placeholder = `![上传中...](${uploadId})`
    
    // 插入占位符
    const beforeText = content.value.substring(0, cursorPosition)
    const afterText = content.value.substring(cursorPosition)
    content.value = beforeText + placeholder + afterText

    // 上传图片
    const formData = new FormData()
    formData.append('image', file)
    
    const response = await apiService.items.uploadImage(formData)
    const imageUrl = response.data.url

    // 替换占位符为实际图片URL
    const finalMarkdown = `![图片](${imageUrl})`
    content.value = content.value.replace(placeholder, finalMarkdown)

    ElMessage.success('图片上传成功')
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败，请重试')
    
    // 移除占位符（使用正则表达式匹配所有上传中的占位符）
    content.value = content.value.replace(/!\[上传中\.\.\.\]\(uploading-[^)]+\)/g, '')
  }
}

// 快捷键支持
const handleKeydown = (event) => {
  if (event.ctrlKey || event.metaKey) {
    switch (event.key) {
      case 's':
        event.preventDefault()
        saveContent()
        break
      case 'b':
        event.preventDefault()
        insertBold()
        break
      case 'i':
        event.preventDefault()
        insertItalic()
        break
      case 'k':
        event.preventDefault()
        insertLink()
        break
    }
  }
}

// 组件挂载时添加快捷键监听
import { onMounted, onUnmounted } from 'vue'

onMounted(() => {
  document.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
/* 图片上传对话框样式 */
.image-upload-content {
  padding: 10px 0;
}

.image-upload-tabs {
  margin-bottom: 20px;
}

.upload-section {
  text-align: center;
}

.image-uploader {
  width: 100%;
}

.upload-area {
  padding: 40px 20px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
  transition: all 0.3s;
}

.upload-area:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.upload-icon {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.upload-text {
  font-size: 16px;
  color: #606266;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 12px;
  color: #909399;
}

.image-preview {
  position: relative;
  display: inline-block;
  max-width: 100%;
}

.image-preview img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.image-actions {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-preview:hover .image-actions {
  opacity: 1;
}

.image-info {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.url-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.url-preview {
  text-align: center;
  margin-top: 16px;
}

.url-preview img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 原有样式 */
.markdown-editor {
  display: flex;
  flex-direction: column;
  height: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

/* 拖拽提示样式 */
.markdown-textarea :deep(textarea) {
  transition: all 0.3s ease;
}

.markdown-textarea :deep(textarea):focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.markdown-textarea :deep(textarea)::placeholder {
  color: #c0c4cc;
}

/* 拖拽悬停效果 */
.markdown-textarea.drag-over :deep(textarea) {
  border-color: #409eff;
  background-color: #f0f9ff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f8f9fa;
}

.editor-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.editor-body {
  flex: 1;
  overflow: hidden;
}

.editor-only,
.preview-only {
  height: 100%;
  padding: 15px;
}

.markdown-textarea {
  height: 100%;
}

.markdown-textarea :deep(.el-textarea__inner) {
  height: 100% !important;
  resize: none;
  font-family: 'Courier New', Courier, monospace;
  font-size: 14px;
  line-height: 1.6;
  border: none;
  box-shadow: none;
}

.markdown-textarea :deep(.el-textarea__inner):focus {
  box-shadow: none;
}

.split-view {
  display: flex;
  height: 100%;
}

.split-editor,
.split-preview {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.split-header {
  padding: 8px 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

.split-editor {
  padding: 0;
}

.split-editor .markdown-textarea {
  flex: 1;
  padding: 15px;
}

.split-divider {
  width: 1px;
  background-color: #ebeef5;
}

.split-preview {
  padding: 0;
}

.markdown-preview {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
  background-color: #fff;
}

.markdown-body {
  line-height: 1.6;
  color: #333;
  font-size: 14px;
}

.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
  margin-top: 24px;
  margin-bottom: 16px;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-body h1 {
  font-size: 2em;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 10px;
}

.markdown-body h2 {
  font-size: 1.5em;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 8px;
}

.markdown-body h3 {
  font-size: 1.25em;
}

.markdown-body p {
  margin-bottom: 16px;
}

.markdown-body code {
  background-color: #f6f8fa;
  border-radius: 3px;
  font-size: 85%;
  margin: 0;
  padding: 0.2em 0.4em;
  font-family: 'Courier New', Courier, monospace;
}

.markdown-body pre {
  background-color: #f6f8fa;
  border-radius: 6px;
  font-size: 85%;
  line-height: 1.45;
  overflow: auto;
  padding: 16px;
  margin-bottom: 16px;
}

.markdown-body pre code {
  background-color: transparent;
  border: 0;
  display: inline;
  line-height: inherit;
  margin: 0;
  max-width: auto;
  overflow: visible;
  padding: 0;
  word-wrap: normal;
}

.markdown-body blockquote {
  border-left: 4px solid #dfe2e5;
  color: #6a737d;
  padding-left: 16px;
  margin: 0 0 16px 0;
}

.markdown-body ul,
.markdown-body ol {
  margin-bottom: 16px;
  padding-left: 2em;
}

.markdown-body li {
  margin-bottom: 4px;
}

.markdown-body a {
  color: #0366d6;
  text-decoration: none;
}

.markdown-body a:hover {
  text-decoration: underline;
}

.markdown-body img {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  margin: 8px 0;
}

.markdown-body hr {
  border: none;
  border-top: 1px solid #eaecef;
  margin: 24px 0;
}

.empty-content {
  color: #909399;
  font-style: italic;
  text-align: center;
  padding: 40px 0;
}

.editor-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 15px;
  border-top: 1px solid #ebeef5;
  background-color: #f8f9fa;
  font-size: 12px;
}

.editor-status {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 滚动条样式 */
.markdown-preview::-webkit-scrollbar {
  width: 8px;
}

.markdown-preview::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.markdown-preview::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.markdown-preview::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .split-view {
    flex-direction: column;
  }
  
  .split-divider {
    width: 100%;
    height: 1px;
  }
  
  .editor-header {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
  
  .editor-actions {
    justify-content: center;
  }
}
</style>